package com.newhopegroup.webcommons.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wangshida on 15/11/5.
 * 临时文件操作帮助类
 */
public class TempFileHelper {

    public static String buildTempFileFullname(String filename) {
        String tempDirectoryPath = FileUtils.getTempDirectoryPath();
        String path = FilenameUtils.concat(tempDirectoryPath, filename);
        File file = new File(path);
        if (!file.exists()) {
            return path;
        } else {
            String time = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date(System.currentTimeMillis()));
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf('.');
                if ((dot > -1) && (dot < (filename.length()))) {
                    filename = filename.substring(0, dot) + "-" + time + file.getName().substring(dot);
                    path = buildTempFileFullname(filename);
                }
            }
            return path;
        }
    }

    public static File createTempFile(String filename) {
        return FileUtils.getFile(buildTempFileFullname(filename));
    }
}
